package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApplicationInfoMapper applicationInfoMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public void login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        //验证用户名和密码是否正确
        User user = userClient.findUsernameAndPassword(username, password);
        //将User对象转成UserInfo对象
        UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), "amdin");
        //构建token并写入到浏览器的cookie中
        buildTokenToCookie(request, response, userInfo);
    }

    //构建token并写入到浏览器的cookie中
    public void buildTokenToCookie(HttpServletRequest request, HttpServletResponse response, UserInfo userInfo) {
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProp.getPrivateKey(), jwtProp.getCookie().getExpire());
        //将token写入到浏览器的cookie中
        CookieUtils.newCookieBuilder()
                .request(request)
                .response(response)
                .httpOnly(true)
                .domain(jwtProp.getCookie().getCookieDomain())
                .name(jwtProp.getCookie().getCookieName())
                .value(token)
                .build();
    }

    public UserInfo verify(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProp.getCookie().getCookieName());
        //解析校验token
        if(StringUtils.isEmpty(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取token的id
        String tokenId = payload.getId();
        //判断当前token的id是否在黑名单
        if(redisTemplate.hasKey(tokenId)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //返回用户信息
        UserInfo userInfo = payload.getUserInfo();
        //获取token的过期时间
        Date expTime = payload.getExpiration();
        //通过过期时间计算出刷新时间
        DateTime refreshTime = new DateTime(expTime).minusMinutes(jwtProp.getCookie().getRefreshTime());
        //如果当前时间在刷新时间之后就刷新token
        if(refreshTime.isBeforeNow()){
            //构建token并写入到浏览器的cookie中
            buildTokenToCookie(request, response, userInfo);
        }
        return userInfo;
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProp.getCookie().getCookieName());
        //解析校验token
        if(StringUtils.isEmpty(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取token的id
        String tokenId = payload.getId();
        //获取过期时间
        Date expDate = payload.getExpiration();
        //获取剩余过期时间
        long remainTime = expDate.getTime() - System.currentTimeMillis();
        //将过期剩余时间超过5秒放入黑名单
        if(remainTime>5000){
            //将token的id放入redis黑名单
            redisTemplate.opsForValue().set(tokenId, "随便写", remainTime, TimeUnit.MILLISECONDS);
        }
        //删除token
        CookieUtils.deleteCookie(jwtProp.getCookie().getCookieName(), jwtProp.getCookie().getCookieDomain(), response);
    }

    /**
     * 校验来访服务的id和密码是否正确
     */
    public Boolean isUsable(Long id, String serviceName){
        //根据id查询服务对象
        ApplicationInfo applicationInfo = applicationInfoMapper.selectById(id);
        if(applicationInfo==null){
            return false;
        }
        //比对密码是否可用
        if(passwordEncoder.matches(serviceName, applicationInfo.getSecret())){
            return true;
        }
        return false;
    }

    public String authorize(Long id, String serviceName) {
        //判断服务id和密钥是否正确
        Boolean isUsable = isUsable(id, serviceName);
        if(!isUsable){
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }
        //获取当前服务可以访问的服务列表
        List<Long> targetIdList = applicationInfoMapper.queryTargetIdList(id);
        //封装AppInfo
        AppInfo appInfo = new AppInfo(id, serviceName, targetIdList);
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(appInfo, jwtProp.getPrivateKey(), jwtProp.getApp().getExpire());
        return token;
    }
}
